import { getTranslate } from './translate'
const inertiaTouch = (el, options) => {
  let prevTranslateX
  let prevTranslateY
  let touchState = {
    touching: false,
    effectEl: options.effectEl || el
  }
  // start
  const onTouchStart = (event, sourceEvent) => {
    if (touchState.touching) return
    let translate = getTranslate(touchState.effectEl)
    Object.assign(touchState, {
      startTimestamp: new Date(),
      pageX: event.pageX,
      pageY: event.pageY,
      translateX: translate.x,
      translateY: translate.y
    })
    if (options.onTouchStart) {
      options.onTouchStart(touchState, sourceEvent)
    }
  }
  // move
  const onTouchMove = (event, sourceEvent) => {
    let deltaX = event.pageX - touchState.pageX
    let deltaY = event.pageY - touchState.pageY
    let translateX = touchState.translateX + deltaX
    let translateY = touchState.translateY + deltaY
    let velocityTranslateX = translateX - prevTranslateX || translateX
    let velocityTranslateY = translateY - prevTranslateY || translateY
    prevTranslateX = translateX
    prevTranslateY = translateY
    Object.assign(touchState, {
      touching: true,
      velocityTranslateX,
      velocityTranslateY
    })
    if (options.onTouchMove) {
      options.onTouchMove({
        ...touchState,
        deltaX,
        deltaY,
        translateX,
        translateY
      }, sourceEvent)
    }
  }
  // end
  const onTouchEnd = (event, sourceEvent) => {
    Object.assign(touchState, {
      touching: false
    })
    if (options.onTouchEnd) {
      options.onTouchEnd(touchState, sourceEvent)
    }
    touchState = {
      touching: false,
      effectEl: options.effectEl || el
    }
  }
  // addEvent
  el.addEventListener('touchstart', event => onTouchStart(event.changedTouches[0] || event.touches[0], event))
  el.addEventListener('touchmove', event => onTouchMove(event.changedTouches[0] || event.touches[0], event))
  el.addEventListener('touchend', event => onTouchEnd(event.changedTouches[0] || event.touches[0], event))
  el.addEventListener('touchcancel', event => onTouchEnd(event.changedTouches[0] || event.touches[0], event))
}
export default inertiaTouch
